package com.ljcalc.business.components;

import java.lang.reflect.*;
import java.net.*;
import java.util.*;

import com.ljcalc.business.components.fetchers.HTTPFetcher;

import static org.easymock.EasyMock.*;

import junit.framework.*;

public class RandomPoolManagerTest extends TestCase{

	private HTTPFetcher fmock = null;
	private RandomPoolManager rpmmock = null;
	
	public void setUp() throws Exception{
		super.setUp();
		fmock = createMock(HTTPFetcher.class);
		RandomPoolManager rpm = RandomPoolManager.getInstance();
		
		Field field = getField(rpm.getClass(), "httpFetcher");
		field.setAccessible(true);
		field.set(rpm, fmock);
	}
	
	public void tearDown() throws Exception{
		super.tearDown();
	}
	
	public void testGenerateRandomPool() throws Exception{

		LinkedList<Long> list = new LinkedList<Long>();
		list.add(new Long(1));
		list.add(new Long(1));
		list.add(new Long(1));
		
		LinkedList<Long> list2 = new LinkedList<Long>();
		list2.add(new Long(2));
		list2.add(new Long(2));
		list2.add(new Long(2));
		
		LinkedList<Long> list3 = new LinkedList<Long>();
		list3.add(new Long(3));
		list3.add(new Long(3));
		list3.add(new Long(3));
		
//		fmock.loadContent();
//		fmock.loadContent();
//		fmock.loadContent();
		
		
		expect(fmock.loadContent()).andReturn(0);
		expect(fmock.loadContent()).andReturn(0);
		expect(fmock.loadContent()).andReturn(0);

		
		expect(fmock.getContent()).andReturn(list);
		expect(fmock.getContent()).andReturn(list2);
		expect(fmock.getContent()).andReturn(list3);
		
		
		replay(fmock);
		
		RandomPoolManager.getInstance().getRandomPool(1,10);
		RandomPoolManager.getInstance().getRandomPool(2,20);
		RandomPoolManager.getInstance().getRandomPool(3,30);
		
		
		assertEquals(1, RandomPoolManager.getInstance().getRandomPool(1,10).getNextRandomValue());
		assertEquals(2, RandomPoolManager.getInstance().getRandomPool(1,10).size());
		assertEquals(2, RandomPoolManager.getInstance().getRandomPool(2,20).getNextRandomValue());
		assertEquals(3, RandomPoolManager.getInstance().getRandomPool(3,30).getNextRandomValue());
		
		verify(fmock);
		
	}
	
	private Field getField(Class clazz, String fieldName) throws NoSuchFieldException {
		try {
			return clazz.getDeclaredField(fieldName);
		} catch (NoSuchFieldException ex) {
			if (!clazz.getSuperclass().equals(Object.class)) {
				return getField(clazz.getSuperclass(), fieldName);
			} else {
				throw ex;
			}
		}
	}

	
}
